/*
 * @Author: hongbin
 * @Date: 2022-11-20 17:35:48
 * @LastEditors: hongbin
 * @LastEditTime: 2022-11-22 12:20:18
 * @Description:添加好友
 */
import { ObjectId } from "mongodb";
import { NextApiRequest, NextApiResponse } from "next";
import { VerifyFields } from "../../../src/api/utils";
import DB from "../mongodb";
import { receiveRequest } from "../utils";

export default async function handler(req: NextApiRequest, res: NextApiResponse<any>) {
    if (!receiveRequest(req, res, "POST")) return;
    // 通过socket发送申请加好友消息同意后双方均执行此请求
    console.log("请求内容", req.body);
    if (!VerifyFields.has(req.body, ["self", "other"])) {
        return res.status(500).json("缺少关键字段");
    }

    const db = await DB;
    const date = Date.now();

    //创建一个两人的聊天室 chatRecord
    const chatRecord = await db.collection("chatRecord").insertOne({
        users: [req.body.self, req.body.other],
        record: [],
    });

    if (!chatRecord.acknowledged) {
        return res.status(200).json({ data: null, msg: "添加好友信息失败", code: -1 });
    }

    // 加对方
    const insertOther = await db.collection("userInfo").updateOne(
        { _id: new ObjectId(req.body.self) },
        {
            $push: {
                friendsList: {
                    date,
                    friendId: new ObjectId(req.body.other),
                    chatRecordId: chatRecord.insertedId,
                },
            },
        }
    );
    console.log("自己添加对方:", insertOther);
    const otherInsert = await db.collection("userInfo").updateOne(
        { _id: new ObjectId(req.body.other) },
        {
            $push: {
                friendsList: {
                    date,
                    friendId: new ObjectId(req.body.self),
                    chatRecordId: chatRecord.insertedId,
                },
            },
        }
    );
    console.log("对方添加自己:", otherInsert);

    if (insertOther.acknowledged && otherInsert.acknowledged) {
        res.status(200).json({ data: { date, chatRecordId: chatRecord.insertedId, msg: "添加好友成功" } });
        return;
    }
    res.status(200).json({ data: null, msg: "添加好友信息失败", code: -1 });
}
